<template>
  <div class="fixed right-6 top-1/2 transform -translate-y-1/2 z-40 hidden lg:block">
    <div class="flex flex-col space-y-4">
      <button v-for="section in sections" :key="section.id" @click="navigateTo(section.id)"
        class="w-3 h-3 rounded-full transition-all duration-300 focus:outline-none" :class="{
          'bg-indigo-600 scale-125': activeSection === section.id,
          'bg-gray-300 hover:bg-gray-400': activeSection !== section.id
        }" :aria-label="`跳转到${section.name}`" />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

const sections = [
  { id: 'swiper', name: '轮播' },
  { id: 'home', name: '首页' },
  { id: 'about', name: '关于我们' },
  { id: 'products', name: '产品服务' },
  { id: 'news', name: '新闻中心' },
  { id: 'contact', name: '联系我们' }
]

const emit = defineEmits(['activeSectionChange'])


const activeSection = ref(sections[0].id)
let observer: IntersectionObserver | null = null

// 处理导航点击
const navigateTo = (id: string) => {
  const element = document.getElementById(id)
  if (element) {
    // 考虑可能有固定导航栏的情况，添加偏移量
    const offset = 80
    const top = element.offsetTop - offset
    window.scrollTo({
      top,
      behavior: 'smooth'
    })
  }
}

// 初始化 IntersectionObserver
const initScrollSpy = () => {
  observer = new IntersectionObserver(
    (entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          activeSection.value = entry.target.id
          emit('activeSectionChange', entry.target.id) // <-- 关键代码
        }
      })
    },
    {
      root: null,
      rootMargin: '0px',
      threshold: 0.5
    }
  )

  // 观察所有目标元素
  sections.forEach(section => {
    const element = document.getElementById(section.id)
    if (element) {
      observer?.observe(element)
    }
  })
}

onMounted(() => {
  initScrollSpy()
})

onUnmounted(() => {
  if (observer) {
    observer.disconnect()
  }
})
</script>


<style scoped>
/* 确保样式优先级 */
.bg-indigo-600 {
  background-color: rgb(79 70 229);
}

.scale-125 {
  transform: scale(1.25);
}

.bg-gray-300 {
  background-color: rgb(209 213 219);
}

.bg-gray-300:hover {
  background-color: rgb(156 163 175);
}
</style>